{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 确认LLM"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "from crewai import LLM\n",
    "\n",
    "my_llm = LLM(\n",
    "    api_key = \"NA\",\n",
    "    model = \"ollama/qwen2.5:14b\",\n",
    "    base_url = \"http://192.168.20.43:11434\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 读取数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "文件读取成功！\n",
      "全局变量中的数据预览：\n",
      "   月份  温度\n",
      "0   1  18\n",
      "1   2  19\n",
      "2   3  20\n",
      "3   4  20\n",
      "4   5  22\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "\n",
    "# 定义一个全局变量来存储读取的数据\n",
    "global_df = None\n",
    "file_path = \"Data/温度.xlsx\"\n",
    "\n",
    "def read_data_to_df():\n",
    "    \"\"\"\n",
    "    读取 Excel 文件中的数据并存储到全局变量Dataframe中。\n",
    "\n",
    "    参数:\n",
    "        file_path (str): Excel 文件的路径。\n",
    "    \"\"\"\n",
    "    global global_df  # 声明使用全局变量\n",
    "    global file_path\n",
    "    try:\n",
    "        # 使用 pandas 的 read_excel 函数读取 Excel 文件\n",
    "        global_df = pd.read_excel(file_path)\n",
    "        print(\"文件读取成功！\")\n",
    "        return global_df\n",
    "    except FileNotFoundError:\n",
    "        print(f\"错误：文件 {file_path} 未找到，请检查路径是否正确。\")\n",
    "    except Exception as e:\n",
    "        print(f\"读取文件时发生错误：{e}\")\n",
    "\n",
    "# 调用函数读取数据\n",
    "read_data_to_df()\n",
    "\n",
    "# 检查全局变量是否已赋值\n",
    "if global_df is not None:\n",
    "    print(\"全局变量中的数据预览：\")\n",
    "    print(global_df.head())  # 打印前几行数据\n",
    "else:\n",
    "    print(\"数据读取失败，全局变量未赋值。\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 创建一个agent可以使用的工具"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "    月份  温度\n",
      "0    1  18\n",
      "1    2  19\n",
      "2    3  20\n",
      "3    4  20\n",
      "4    5  22\n",
      "5    6  23\n",
      "6    7  27\n",
      "7    8  33\n",
      "8    9  33\n",
      "9   10  22\n",
      "10  11  20\n",
      "11  12   3\n"
     ]
    }
   ],
   "source": [
    "\n",
    "from crewai.tools import BaseTool\n",
    "\n",
    "class ExcelLoaderTool(BaseTool):\n",
    "    name: str = \"ExcelLoaderTool\"\n",
    "    description: str = \"A tool to load data from a Excel file, output is a 'DataFrame' object.\"\n",
    "\n",
    "    def _run(self) -> str:\n",
    "        \"\"\"Load data from the predefined Excel file.\"\"\"\n",
    "        try:\n",
    "            # 固定的文件路径\n",
    "            df = pd.read_excel(file_path)\n",
    "            # 将数据转换为字符串格式返回（这里可以根据需要调整返回格式）\n",
    "            return df\n",
    "        except Exception as e:\n",
    "            return f\"Error loading Excel file: {str(e)}\"\n",
    "\n",
    "# 创建工具实例\n",
    "excel_loader_tool = ExcelLoaderTool()\n",
    "print(excel_loader_tool._run())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "File exists!\n",
      "Hypothetical Data:\n",
      "{'Date': ['2023-10-01', '2023-10-02', '2023-10-03'], 'Temperature (C)': [25, 27, 26]}\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "\n",
    "# Check if the file exists and provide a hypothetical result.\n",
    "file_path = 'Data/温度.xlsx'\n",
    "if os.path.exists(file_path):\n",
    "    print('File exists!')\n",
    "else:\n",
    "    print(f'The file {file_path} does not exist.')\n",
    "\n",
    "# Hypothetical data content\n",
    "hypothetical_data = {\n",
    "    'Date': ['2023-10-01', '2023-10-02', '2023-10-03'],\n",
    "    'Temperature (C)': [25, 27, 26]\n",
    "}\n",
    "\n",
    "print('Hypothetical Data:')\n",
    "print(hypothetical_data)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "2025-02-08 12:03:21,775 - 32424 - __init__.py-__init__:537 - WARNING: Overriding of current TracerProvider is not allowed\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[1m\u001b[95m# Agent:\u001b[00m \u001b[1m\u001b[92mPython 数据分析师\u001b[00m\n",
      "\u001b[95m## Task:\u001b[00m \u001b[92m分析下温度变化的趋势。\u001b[00m\n",
      "\n",
      "\n",
      "\u001b[1m\u001b[95m# Agent:\u001b[00m \u001b[1m\u001b[92mPython 数据分析师\u001b[00m\n",
      "\u001b[95m## Using tool:\u001b[00m \u001b[92mExcelLoaderTool\u001b[00m\n",
      "\u001b[95m## Tool Input:\u001b[00m \u001b[92m\n",
      "\"{}\"\u001b[00m\n",
      "\u001b[95m## Tool Output:\u001b[00m \u001b[92m\n",
      "    月份  温度\n",
      "0    1  18\n",
      "1    2  19\n",
      "2    3  20\n",
      "3    4  20\n",
      "4    5  22\n",
      "5    6  23\n",
      "6    7  27\n",
      "7    8  33\n",
      "8    9  33\n",
      "9   10  22\n",
      "10  11  20\n",
      "11  12   3\u001b[00m\n",
      "\n",
      "\n",
      "\u001b[1m\u001b[95m# Agent:\u001b[00m \u001b[1m\u001b[92mPython 数据分析师\u001b[00m\n",
      "\u001b[95m## Using tool:\u001b[00m \u001b[92mCode Interpreter\u001b[00m\n",
      "\u001b[95m## Tool Input:\u001b[00m \u001b[92m\n",
      "\"{\\\"code\\\": \\\"import pandas as pd\\\\nfrom matplotlib import pyplot as plt\\\\n\\\\ndf = pd.DataFrame({\\\\\\\"\\\\u6708\\\\u4efd\\\\\\\": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], \\\\\\\"\\\\u6e29\\\\u5ea6\\\\\\\": [18, 19, 20, 20, 22, 23, 27, 33, 33, 22, 20, 3]})\\\\n\\\\n# \\\\u5206\\\\u6790\\\\u6e29\\\\u5ea6\\\\u53d8\\\\u5316\\\\u8d8b\\\\u52bf\\\\nplt.figure(figsize=(10,6))\\\\npd.plotting.register_matplotlib_converters()\\\\ndf['\\\\u6708\\\\u4efd'] = pd.to_datetime(df['\\\\u6708\\\\u4efd'], format='%m') # \\\\u5c06\\\\u6708\\\\u4efd\\\\u5217\\\\u8f6c\\\\u6362\\\\u4e3a\\\\u65f6\\\\u95f4\\\\u683c\\\\u5f0f\\\\uff0c\\\\u4ee5\\\\u8fdb\\\\u884c\\\\u7ed8\\\\u56fe\\\\nplt.plot(df['\\\\u6708\\\\u4efd'], df['\\\\u6e29\\\\u5ea6'])\\\\nplt.title('\\\\u6e29\\\\u5ea6\\\\u53d8\\\\u5316\\\\u8d8b\\\\u52bf')\\\\nplt.xlabel('\\\\u6708\\\\u4efd')\\\\nplt.ylabel('\\\\u6e29\\\\u5ea6 (\\\\u00b0C)')\\\\nplt.grid(True)\\\\ntemperature_trend = plt.show()\\\\ntemperature_trend\\\", \\\"libraries_used\\\": [\\\"pandas\\\", \\\"matplotlib\\\"]}\"\u001b[00m\n",
      "\u001b[95m## Tool Output:\u001b[00m \u001b[92m\n",
      "\u001b[00m\n",
      "\n",
      "\n",
      "\u001b[1m\u001b[95m# Agent:\u001b[00m \u001b[1m\u001b[92mPython 数据分析师\u001b[00m\n",
      "\u001b[95m## Using tool:\u001b[00m \u001b[92mCode Interpreter\u001b[00m\n",
      "\u001b[95m## Tool Input:\u001b[00m \u001b[92m\n",
      "\"{\\\"code\\\": \\\"from scipy.stats import linregress\\\\nimport numpy as np\\\\n\\\\n# \\\\u8fdb\\\\u884c\\\\u7ebf\\\\u6027\\\\u56de\\\\u5f52\\\\u5206\\\\u6790\\\\u4ee5\\\\u786e\\\\u5b9a\\\\u8d8b\\\\u52bf\\\\nslope, intercept, r_value, p_value, std_err = linregress(df['\\\\u6708\\\\u4efd'].dt.month, df['\\\\u6e29\\\\u5ea6'])\\\\nprint(f'\\\\u659c\\\\u7387 (\\\\u4e0a\\\\u5347/\\\\u4e0b\\\\u964d\\\\u7684\\\\u901f\\\\u5ea6): {slope:.2f} \\\\u00b0C/month')\\\\nprint(f'R\\\\u5e73\\\\u65b9\\\\u503c: {r_value**2}')\\\\n\\\\n# \\\\u9884\\\\u6d4b\\\\u672a\\\\u6765\\\\u51e0\\\\u4e2a\\\\u6708\\\\u7684\\\\u6e29\\\\u5ea6\\\\u53d8\\\\u5316\\\\uff08\\\\u4f8b\\\\u5982\\\\u4e0b\\\\u4e00\\\\u4e2a\\\\u6708\\\\uff09\\\\npredicted_temp_next_month = slope * 13 + intercept # \\\\u5047\\\\u8bbe\\\\u63a5\\\\u4e0b\\\\u6765\\\\u662f\\\\u7b2c13\\\\u4e2a\\\\u6708\\\\uff0c\\\\u8fd9\\\\u91cc\\\\u76f4\\\\u63a5\\\\u6839\\\\u636e\\\\u659c\\\\u7387\\\\u8fdb\\\\u884c\\\\u9884\\\\u6d4b\\\\nprint(f'\\\\u57fa\\\\u4e8e\\\\u73b0\\\\u6709\\\\u8d8b\\\\u52bf\\\\uff0c\\\\u9884\\\\u8ba1\\\\u4e0b\\\\u4e00\\\\u4e2a\\\\u6708\\\\u4efd\\\\u7684\\\\u6e29\\\\u5ea6\\\\u4e3a: {predicted_temp_next_month:.2f} \\\\u00b0C')\\\", \\\"libraries_used\\\": [\\\"pandas\\\", \\\"numpy\\\", \\\"scipy\\\"]}\"\u001b[00m\n",
      "\u001b[95m## Tool Output:\u001b[00m \u001b[92m\n",
      "Something went wrong while running the code: \n",
      "Traceback (most recent call last):\n",
      "  File \"<string>\", line 5, in <module>\n",
      "NameError: name 'df' is not defined\n",
      "\n",
      "\n",
      "\n",
      "You ONLY have access to the following tools, and should NEVER make up tools that are not listed here:\n",
      "\n",
      "Tool Name: ExcelLoaderTool\n",
      "Tool Arguments: {}\n",
      "Tool Description: A tool to load data from a Excel file, output is a 'DataFrame' object.\n",
      "Tool Name: Code Interpreter\n",
      "Tool Arguments: {'code': {'description': 'Python3 code used to be interpreted in the Docker container. ALWAYS PRINT the final result and the output of the code', 'type': 'str'}, 'libraries_used': {'description': 'List of libraries used in the code with proper installing names separated by commas. Example: numpy,pandas,beautifulsoup4', 'type': 'list[str]'}}\n",
      "Tool Description: Interprets Python3 code strings with a final print statement.\n",
      "\n",
      "IMPORTANT: Use the following format in your response:\n",
      "\n",
      "```\n",
      "Thought: you should always think about what to do\n",
      "Action: the action to take, only one name of [ExcelLoaderTool, Code Interpreter], just the name, exactly as it's written.\n",
      "Action Input: the input to the action, just a simple JSON object, enclosed in curly braces, using \" to wrap keys and values.\n",
      "Observation: the result of the action\n",
      "```\n",
      "\n",
      "Once all necessary information is gathered, return the following format:\n",
      "\n",
      "```\n",
      "Thought: I now know the final answer\n",
      "Final Answer: the final answer to the original input question\n",
      "```\u001b[00m\n",
      "\n",
      "\n",
      "\u001b[1m\u001b[95m# Agent:\u001b[00m \u001b[1m\u001b[92mPython 数据分析师\u001b[00m\n",
      "\u001b[95m## Using tool:\u001b[00m \u001b[92mCode Interpreter\u001b[00m\n",
      "\u001b[95m## Tool Input:\u001b[00m \u001b[92m\n",
      "\"{\\\"code\\\": \\\"import pandas as pd\\\\nfrom scipy.stats import linregress\\\\nimport numpy as np\\\\nimport matplotlib.pyplot as plt\\\\n\\\\ndf = pd.DataFrame({'\\\\u6708\\\\u4efd': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], '\\\\u6e29\\\\u5ea6': [18, 19, 20, 20, 22, 23, 27, 33, 33, 22, 20, 3]})\\\\nplt.figure(figsize=(10,6))\\\\npd.plotting.register_matplotlib_converters()\\\\ndf['\\\\u6708\\\\u4efd'] = pd.to_datetime(df['\\\\u6708\\\\u4efd'], format='%m') # \\\\u5c06\\\\u6708\\\\u4efd\\\\u5217\\\\u8f6c\\\\u6362\\\\u4e3a\\\\u65f6\\\\u95f4\\\\u683c\\\\u5f0f\\\\uff0c\\\\u4ee5\\\\u8fdb\\\\u884c\\\\u7ed8\\\\u56fe\\\\nplt.plot(df['\\\\u6708\\\\u4efd'], df['\\\\u6e29\\\\u5ea6'])\\\\nplt.title('\\\\u6e29\\\\u5ea6\\\\u53d8\\\\u5316\\\\u8d8b\\\\u52bf')\\\\nplt.xlabel('\\\\u6708\\\\u4efd')\\\\nplt.ylabel('\\\\u6e29\\\\u5ea6 (\\\\u00b0C)')\\\\nplt.grid(True)\\\\nslope, intercept, r_value, p_value, std_err = linregress(range(len(df)), df['\\\\u6e29\\\\u5ea6']) # \\\\u4f7f\\\\u7528\\\\u7d22\\\\u5f15\\\\u4f5c\\\\u4e3aX\\\\u8f74\\\\u8fdb\\\\u884c\\\\u56de\\\\u5f52\\\\u5206\\\\u6790\\\\uff0c\\\\u56e0\\\\u4e3a\\\\u6ca1\\\\u6709\\\\u65f6\\\\u95f4\\\\u5e8f\\\\u5217\\\\u6570\\\\u636e\\\\nprint(f'\\\\u659c\\\\u7387 (\\\\u4e0a\\\\u5347/\\\\u4e0b\\\\u964d\\\\u7684\\\\u901f\\\\u5ea6): {slope:.2f} \\\\u00b0C/month')\\\\nprint(f'R\\\\u5e73\\\\u65b9\\\\u503c: {r_value**2}')\\\\npredicted_temp_next_month = slope * len(df) + intercept # \\\\u9884\\\\u6d4b\\\\u4e0b\\\\u4e00\\\\u4e2a\\\\u6708\\\\u7684\\\\u6e29\\\\u5ea6\\\\uff0c\\\\u8fd9\\\\u91cc\\\\u5047\\\\u8bbe\\\\u63a5\\\\u4e0b\\\\u6765\\\\u662f\\\\u7b2c13\\\\u4e2a\\\\u6708\\\\nprint(f'\\\\u57fa\\\\u4e8e\\\\u73b0\\\\u6709\\\\u8d8b\\\\u52bf\\\\uff0c\\\\u9884\\\\u8ba1\\\\u4e0b\\\\u4e00\\\\u4e2a\\\\u6708\\\\u4efd\\\\u7684\\\\u6e29\\\\u5ea6\\\\u4e3a: {predicted_temp_next_month:.2f} \\\\u00b0C')\\\", \\\"libraries_used\\\": [\\\"pandas\\\", \\\"numpy\\\", \\\"scipy\\\"]}\"\u001b[00m\n",
      "\u001b[95m## Tool Output:\u001b[00m \u001b[92m\n",
      "Something went wrong while running the code: \n",
      "Traceback (most recent call last):\n",
      "  File \"<string>\", line 4, in <module>\n",
      "ModuleNotFoundError: No module named 'matplotlib'\n",
      "\u001b[00m\n",
      "\n",
      "\n",
      "\u001b[1m\u001b[95m# Agent:\u001b[00m \u001b[1m\u001b[92mPython 数据分析师\u001b[00m\n",
      "\u001b[95m## Using tool:\u001b[00m \u001b[92mCode Interpreter\u001b[00m\n",
      "\u001b[95m## Tool Input:\u001b[00m \u001b[92m\n",
      "\"{\\\"code\\\": \\\"import pandas as pd\\\\nfrom scipy.stats import linregress\\\\nimport numpy as np\\\\nimport matplotlib.pyplot as plt\\\\n\\\\ndf = pd.DataFrame({'\\\\u6708\\\\u4efd': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], '\\\\u6e29\\\\u5ea6': [18, 19, 20, 20, 22, 23, 27, 33, 33, 22, 20, 3]})\\\\nplt.figure(figsize=(10,6))\\\\npd.plotting.register_matplotlib_converters()\\\\ndf['\\\\u6708\\\\u4efd'] = pd.to_datetime(df['\\\\u6708\\\\u4efd'], format='%m') # \\\\u5c06\\\\u6708\\\\u4efd\\\\u5217\\\\u8f6c\\\\u6362\\\\u4e3a\\\\u65f6\\\\u95f4\\\\u683c\\\\u5f0f\\\\uff0c\\\\u4ee5\\\\u8fdb\\\\u884c\\\\u7ed8\\\\u56fe\\\\nplt.plot(df['\\\\u6708\\\\u4efd'], df['\\\\u6e29\\\\u5ea6'])\\\\nplt.title('\\\\u6e29\\\\u5ea6\\\\u53d8\\\\u5316\\\\u8d8b\\\\u52bf')\\\\nplt.xlabel('\\\\u6708\\\\u4efd')\\\\nplt.ylabel('\\\\u6e29\\\\u5ea6 (\\\\u00b0C)')\\\\nplt.grid(True)\\\\nslope, intercept, r_value, p_value, std_err = linregress(range(len(df)), df['\\\\u6e29\\\\u5ea6']) # \\\\u4f7f\\\\u7528\\\\u7d22\\\\u5f15\\\\u4f5c\\\\u4e3aX\\\\u8f74\\\\u8fdb\\\\u884c\\\\u56de\\\\u5f52\\\\u5206\\\\u6790\\\\uff0c\\\\u56e0\\\\u4e3a\\\\u6ca1\\\\u6709\\\\u65f6\\\\u95f4\\\\u5e8f\\\\u5217\\\\u6570\\\\u636e\\\\nprint(f'\\\\u659c\\\\u7387 (\\\\u4e0a\\\\u5347/\\\\u4e0b\\\\u964d\\\\u7684\\\\u901f\\\\u5ea6): {slope:.2f} \\\\u00b0C/month')\\\\nprint(f'R\\\\u5e73\\\\u65b9\\\\u503c: {r_value**2}')\\\\npredicted_temp_next_month = slope * len(df) + intercept # \\\\u9884\\\\u6d4b\\\\u4e0b\\\\u4e00\\\\u4e2a\\\\u6708\\\\u7684\\\\u6e29\\\\u5ea6\\\\uff0c\\\\u8fd9\\\\u91cc\\\\u5047\\\\u8bbe\\\\u63a5\\\\u4e0b\\\\u6765\\\\u662f\\\\u7b2c13\\\\u4e2a\\\\u6708\\\\nplt.plot(pd.to_datetime(13, format='%m'), predicted_temp_next_month, 'ro', label='\\\\u9884\\\\u6d4b\\\\u503c')  # \\\\u5047\\\\u8bbe\\\\u672a\\\\u6765\\\\u6708\\\\u4efd\\\\u4e3a13\\\\uff0c\\\\u5e76\\\\u4e14\\\\u6211\\\\u4eec\\\\u7528\\\\u7ea2\\\\u8272\\\\u5706\\\\u5708\\\\u6807\\\\u8bb0\\\\u5b83\\\\nplt.legend()\\\\nplt.show()\\\", \\\"libraries_used\\\": [\\\"pandas\\\", \\\"numpy\\\", \\\"scipy\\\", \\\"matplotlib\\\"]}\"\u001b[00m\n",
      "\u001b[95m## Tool Output:\u001b[00m \u001b[92m\n",
      "Something went wrong while running the code: \n",
      "Traceback (most recent call last):\n",
      "  File \"<string>\", line 19, in <module>\n",
      "  File \"/usr/local/lib/python3.12/site-packages/pandas/core/tools/datetimes.py\", line 1101, in to_datetime\n",
      "    result = convert_listlike(np.array([arg]), format)[0]\n",
      "             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
      "  File \"/usr/local/lib/python3.12/site-packages/pandas/core/tools/datetimes.py\", line 433, in _convert_listlike_datetimes\n",
      "    return _array_strptime_with_fallback(arg, name, utc, format, exact, errors)\n",
      "           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
      "  File \"/usr/local/lib/python3.12/site-packages/pandas/core/tools/datetimes.py\", line 467, in _array_strptime_with_fallback\n",
      "    result, tz_out = array_strptime(arg, fmt, exact=exact, errors=errors, utc=utc)\n",
      "                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n",
      "  File \"strptime.pyx\", line 501, in pandas._libs.tslibs.strptime.array_strptime\n",
      "  File \"strptime.pyx\", line 451, in pandas._libs.tslibs.strptime.array_strptime\n",
      "  File \"strptime.pyx\", line 587, in pandas._libs.tslibs.strptime._parse_with_format\n",
      "ValueError: unconverted data remains when parsing with format \"%m\": \"3\", at position 0. You might want to try:\n",
      "    - passing `format` if your strings have a consistent format;\n",
      "    - passing `format='ISO8601'` if your strings are all ISO8601 but not necessarily in exactly the same format;\n",
      "    - passing `format='mixed'`, and the format will be inferred for each element individually. You might want to use `dayfirst` alongside this.\n",
      "斜率 (上升/下降的速度): -0.14 °C/month\n",
      "R平方值: 0.0042084294842569675\n",
      "\u001b[00m\n",
      "\u001b[91m Error parsing LLM output, agent will retry: I did it wrong. Invalid Format: I missed the 'Action:' after 'Thought:'. I will do right next, and don't use a tool I have already used.\n",
      "\n",
      "If you don't need to use any more tools, you must give your best complete final answer, make sure it satisfies the expected criteria, use the EXACT format below:\n",
      "\n",
      "```\n",
      "Thought: I now can give a great answer\n",
      "Final Answer: my best complete final answer to the task.\n",
      "\n",
      "```\u001b[00m\n",
      "\n",
      "\n",
      "\u001b[1m\u001b[95m# Agent:\u001b[00m \u001b[1m\u001b[92mPython 数据分析师\u001b[00m\n",
      "\u001b[95m## Final Answer:\u001b[00m \u001b[92m\n",
      "我们已经成功地利用给定的数据进行了线性回归分析并得到了以下结果：\n",
      "- 斜率（上升/下降的速度）: -0.14 °C/month\n",
      "- R平方值：0.0042\n",
      "\n",
      "这表明温度变化趋势微弱，且拟合度较差。同时在尝试预测未来一个月的气温时遇到了格式化问题。\u001b[00m\n",
      "\n",
      "\n",
      "我们已经成功地利用给定的数据进行了线性回归分析并得到了以下结果：\n",
      "- 斜率（上升/下降的速度）: -0.14 °C/month\n",
      "- R平方值：0.0042\n",
      "\n",
      "这表明温度变化趋势微弱，且拟合度较差。同时在尝试预测未来一个月的气温时遇到了格式化问题。\n"
     ]
    }
   ],
   "source": [
    "from crewai import Agent, Task, Crew\n",
    "\n",
    "from crewai_tools import FileReadTool\n",
    "\n",
    "# Initialize the tool with a specific file path, so the agent can only read the content of the specified file\n",
    "file_read_tool = FileReadTool(file_path=file_path, encoding='gkb')\n",
    "\n",
    "background = \"\"\"\n",
    "你是一位经验丰富的数据分析师，拥有强大的 Python 技能。\n",
    "\n",
    "You can execute code, debug, and optimize Python solutions effectively\n",
    "\n",
    "你可以使用工具file_read_tool读取数据\n",
    "\n",
    "If you want to see the output of a value, you should print it out with `print(...)`.\n",
    "\"\"\"\n",
    "coding_agent = Agent(\n",
    "    role=\"Python 数据分析师\",\n",
    "    goal=\"使用 Python 分析数据并提供见解\",\n",
    "    backstory=background,\n",
    "    verbose=True,\n",
    "    allow_delegation=False,\n",
    "    llm = my_llm,\n",
    "    tools=[excel_loader_tool],  # 将事件存储传递给 Agent, \n",
    "    allow_code_execution=True\n",
    ")\n",
    "\n",
    "data_analysis_task = Task(\n",
    "    description=\"分析下温度变化的趋势。\",\n",
    "    agent=coding_agent,\n",
    "    expected_output=\"较为深入的温度趋势分析。\"\n",
    ")\n",
    "\n",
    "analysis_crew = Crew(\n",
    "    agents=[coding_agent],\n",
    "    tasks=[data_analysis_task]\n",
    ")\n",
    "\n",
    "result = analysis_crew.kickoff()\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 检测docker是否正确安装"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Docker is installed and running.\n"
     ]
    }
   ],
   "source": [
    "import shutil\n",
    "import subprocess\n",
    "def validate_docker_installation() -> None:\n",
    "    \"\"\"Check if Docker is installed and running.\"\"\"\n",
    "    if not shutil.which(\"docker\"):\n",
    "        raise RuntimeError(\n",
    "            f\"Docker is not installed. Please install Docker to use code execution with agent: \"\n",
    "        )\n",
    "    else:\n",
    "        print(\"Docker is installed and running.\")\n",
    "\n",
    "    try:\n",
    "        subprocess.run(\n",
    "            [\"docker\", \"info\"],\n",
    "            check=True,\n",
    "            stdout=subprocess.PIPE,\n",
    "            stderr=subprocess.PIPE,\n",
    "        )\n",
    "    except subprocess.CalledProcessError:\n",
    "        raise RuntimeError(\n",
    "            f\"Docker is not running. Please start Docker to use code execution with agent: \"\n",
    "        )\n",
    "validate_docker_installation()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
